import {Component, OnInit, Input, Output, EventEmitter,  OnChanges} from '@angular/core';
import {LayersListService} from './layers-list.service';
import {NzMessageService} from 'ng-zorro-antd';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpService} from '@kylin/http';


@Component({
    selector: 'kylin-layers-list',
    templateUrl: './layers-list.component.html',
    styleUrls: ['./layers-list.component.less']
})
export class LayersListComponent implements OnInit,  OnChanges {
    @Input() LayersGeoJson;   // Geojson数据组
    @Input() LayersListDataLayers;
    layerGeojson = [];
    @Output() newLayersFun = new EventEmitter<any>();
    @Output() deteleLayFun = new EventEmitter<any>();
    @Output() issueLayerUpDataFun = new EventEmitter<any>();
    @Output() selectFeatureFun = new EventEmitter<any>();
    @Output() visibility = new EventEmitter<any>();
    issueLayersShow = false;
    issueLayersForm: FormGroup;
    loading = false;
    issueLayersData: any;
    listOfOption: Array<{label: string; value: number}> = [];
    tagValue = [];
    eyeid;
    constructor(private  layersListService: LayersListService,
                private fb: FormBuilder,
                private message: NzMessageService,
                private http: HttpService) {
    }

    ngOnChanges(changes) {
        this.layerGeojson = [];
        this.handleGeoJsonLayer().then((data: any) => {
            this.layerGeojson = data
    });
    }

    ngOnInit() {
        // 模拟标签
        this.getLayerLabel().then((data: any) => {
            this.listOfOption = data;
        });
        // const children: Array<{ label: string; value: number }> = [];
        // for (let i = 10; i < 36; i++) {
        //     children.push({ label: i.toString(36) + i, value: i });
        // }
        // this.listOfOption = children;
        this.getissueLayersForm();
    }

    getLayerLabel() {
        return new Promise((resolve) => {
            this.http.get('/layerLabel/pageList', ({size: 9999, current: 1} as any)).then(rep => {
                if (rep.resp_code === '10000') {
                    const arr = [];
                    const records: any = (rep.data.records || []);
                    records.map(user => {
                        const labelobj: any = {};
                        labelobj.label = user.labelName;
                        labelobj.value = user.labelId;
                        arr.push(labelobj)
                    })
                    resolve(arr);
                } else {
                    this.message.error('获取标签列表失败，' + rep.resp_msg);
                }
            });
        })
    }

    getissueLayersForm(layerName?) {
        this.issueLayersForm = this.fb.group({
            labelIds: [null, [Validators.required]],
            labelName: [null, [Validators.required]],
            layersName: [layerName, [Validators.required]]
        });
    }

    handleGeoJsonLayer() {
        return new Promise((resolve) => {
            if (this.LayersGeoJson) {
                this.LayersGeoJson.map(layer => {
                    if (layer.layerJson && typeof layer.layerJson === 'string') {
                        layer.layerJson = JSON.parse(layer.layerJson);
                        if (layer.visibilit) {
                            layer.visibilit = true;
                        } else if (layer.visibilit === undefined) {
                            layer.visibilit = true;
                        } else {
                            layer.visibilit = false;
                        }
                        this.visibility.emit([layer.layerId, layer.visibilit]);
                    }
                });
            }
            resolve(this.LayersGeoJson)
        })
    }


    // 新增图层
    newLayersData() {
        this.newLayersFun.emit(true)
    }


    confirm(id) {
        this.deteleLayFun.emit(id);
    }

    // 图层发布
    issueLayers(layer: any) {
        this.issueLayersData = layer;
        this.issueLayersShow = true;
        this.getissueLayersForm(layer.layerName);
    }

    // 取消图层发布
    handleCancel() {
        this.issueLayersShow = false;
    }

    // 提交数据
    submitLayers() {
        this.loading = true;
        const issue = this.issueLayersData.layerName;
        const issuelayer = this.issueLayersData;
        return new Promise((resolve) => {
            issuelayer.layerName = this.issueLayersForm.value.layersName;
            resolve(this.issueLayersForm)
        }).then((data: any) => {
            data.removeControl('layersName');
            data.value.layer = issuelayer;
            this.layersListService.issueLayers(data.value).then((rep) => {
                if (rep.resp_code === '10000') {
                    this.message.success('发布图层成功', rep.resp_msg);
                    this.issueLayersShow = false;
                    this.issueLayerUpDataFun.emit();
                } else {
                    this.issueLayersData.layerName = issue;
                    this.message.create('error', rep.resp_msg);
                    this.issueLayersShow = false;
                }
                this.loading = false;
            }).catch(rep => {
                this.loading = false;
            });
        })



    }


    // 显示/隐藏图层
    showLayers(layer) {
        this.eyeid = layer.layerId;
        this.visibility.emit([this.eyeid, null]);

        this.LayersGeoJson.map(data => {
            if (this.eyeid === data.layerId) {
               data.visibilit = !data.visibilit
            }
        });
    }


    // 选中要素
    selectFeature( layerid, feature) {
        const selectDat = {
            layerid: layerid,
            feature: feature
        };
        this.selectFeatureFun.emit(selectDat);
    }

}
